package com.example.library.controller;

import com.example.library.entity.Book;
import com.example.library.entity.Borrowing;
import com.example.library.entity.User;
import com.example.library.mapper.BookMapper;
import com.example.library.service.IBorrowingService;
import com.example.library.service.IUserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author sx
 * @since 2024-12-17
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;
    @Autowired
    private BookMapper bookMapper;
    @Autowired
    private IBorrowingService borrowingService;

    //用户登录
//    @PostMapping("/login")
//    public ResponseEntity<?> Userlogin(@RequestParam String name,@RequestParam String password){
//        try {
//            User user = userService.Userlogin(name, password);
//            if (user != null) {
//                return ResponseEntity.ok(user);
//            } else {
//                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid username or password");
//            }
//        } catch (Exception e) {
//            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error logging in: " + e.getMessage());
//        }
//    }

    // 获取当前登录用户的个人信息
    @GetMapping("/profile")
    public ResponseEntity<?> getProfile() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        ;
        if (authentication == null || !authentication.isAuthenticated()) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("No user is currently logged in");
        }

        // 从认证对象中获取用户名
        Object principal = authentication.getPrincipal();
        String name;

        if (principal instanceof UserDetails) {
            name = ((UserDetails) principal).getUsername();
        } else {
            name = principal.toString();
        }

        User user = userService.findByName(name);
        if(user != null){
            return  ResponseEntity.ok(user);
        }
        else{
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("No admin found for the current session");
        }

    }

//    /**
//     * 更新当前登录管理员的个人信息
//     * @param updatedUser 更新后的管理员信息
//     * @return 更新后的管理员信息
//     */
//    @PutMapping("/update")
//    public ResponseEntity<?> updateProfile(@RequestBody User updatedUser) {
//        try {
//            // 获取当前登录用户信息
//            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//            if (authentication == null || !authentication.isAuthenticated()) {
//                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("No admin is currently logged in");
//            }
//
//            Object principal = authentication.getPrincipal();
//            String name;
//
//            if (principal instanceof UserDetails) {
//                name = ((UserDetails) principal).getUsername();
//            } else {
//                name = principal.toString();
//            }
//
//            // 根据用户名更新管理员信息
//            updatedUser.setName(name);
//            User updated = userService.updateProfile(updatedUser);
//
//            return ResponseEntity.ok(updated);
//        } catch (Exception e) {
//            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error updating admin profile: " + e.getMessage());
//        }
//    }
//
//
//    // 借阅书籍
//    @PostMapping("/borrow")
//    public ResponseEntity<?> borrowBook(@RequestParam Integer userId, @RequestParam Integer bookId) {
//        Book book = bookMapper.selectByID(bookId);
//        if (book == null) {
//            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Book not found");
//        }
//
//        // 检查书籍是否可借
//        if (book.getCount() <= 0) {
//            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Book is out of stock");
//        }
//
//        // 创建借阅记录
//        Borrowing borrowing = new Borrowing();
//        borrowing.setUserid(Math.toIntExact(userId));
//        borrowing.setBookid(Math.toIntExact(bookId));
//        borrowing.setBorrowdate(new java.util.Date());
//        borrowing.setReturndate(null);  // 未归还
//
//        boolean isSuccess = borrowingService.save(borrowing);
//        if (isSuccess) {
//            // 更新书籍库存
//            book.setCount(book.getCount() - 1);
//            bookMapper.updateByPrimaryKey(book);
//
//            return ResponseEntity.ok("Book borrowed successfully");
//        } else {
//            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error borrowing book");
//        }
//    }
//
//    // 归还书籍
//    @PostMapping("/return")
//    public ResponseEntity<?> returnBook(@RequestParam Integer userId, @RequestParam Integer bookId) {
//        // 查找借阅记录
//        Borrowing borrowing = borrowingService.getActiveBorrowing(userId, bookId);
//        if (borrowing == null) {
//            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Borrowing record not found");
//        }
//
//        // 归还书籍并更新库存
//        borrowing.setReturndate(new java.util.Date());  // 设置归还日期
//        boolean isSuccess = borrowingService.updateById(borrowing);
//        if (isSuccess) {
//            Book book = bookMapper.selectByID(bookId);
//            book.setCount(book.getCount() + 1);
//            bookMapper.updateByPrimaryKey(book);
//            return ResponseEntity.ok("Book returned successfully");
//        } else {
//            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error returning book");
//        }
//    }
}
